package singleton;

import org.springframework.objenesis.instantiator.util.UnsafeUtils;

import java.io.*;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;

public class TestUtil {
    public static void unsafe(Class<?> clazz) throws InstantiationException {
        //这里需要借助Spring提供的UnsafeUtils拿到Unsafe对象,该方法同样不走构造方法，无法避免
        Object o = UnsafeUtils.getUnsafe().allocateInstance(clazz);
        System.out.println("Unsafe创建实例:"+ o);
    }

    public static void serializable(Object instance) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(instance);
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(bos.toByteArray()));
        //该新对象的创建不走构造方法
        //然而要注意当执行readObject方法时，会去原类里寻找readResolve方法，如果找到走该方法逻辑，如果该方法不存在则直接创建新对象
        System.out.println("反序列化创建实例："+ ois.readObject());
    }

    public static void reflection(Class<?> clazz) throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        Constructor<?> constructor = clazz.getDeclaredConstructor();
        constructor.setAccessible(true);  //修改访问权限
        System.out.println("反射获得实例："+constructor.newInstance());
    }
}
